﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IEMSOFT.EasyHotel.DAL.Models;
using IEMSOFT.EasyHotel.DAL.Models.Extension;
namespace IEMSOFT.EasyHotel.DAL
{
    public class RoomDAL
    {
        private  IDBProvider _dbProvider;
        public RoomDAL(IDBProvider dbProvider)
        {
            _dbProvider = dbProvider;
        }

        public List<RoomExtension> GetList(int subHotelId)
        {
            var sql = new StringBuilder();
            sql.Append(GetRoomBasicSql());
            sql.Append("where r.SubHotelId=@0 order by r.RoomTypeId, r.RoomNo ASC,r.roomId asc ");
            var ret = _dbProvider.DB.Fetch<RoomExtension>(sql.ToString(), subHotelId);
            return ret ?? new List<RoomExtension>();
        }

        private string GetRoomBasicSql()
        {
            var sql = new StringBuilder();
            sql.Append("select r.*,rt.Name as RoomTypeName,sh.Name as SubHotelName,");
            sql.Append(" sh.Phone as SubHotelPhone,sh.Fax as SubHotelFax,sh.Address as SubHotelAddress ");
            sql.Append("from Room r inner join RoomType rt on r.RoomTypeId=rt.RoomTypeId ");
            sql.Append("    inner join SubHotel sh on sh.SubHotelId=r.SubHotelId ");
            return sql.ToString();
        }

        public void Add (Room room)
        {
            _dbProvider.DB.Insert(room);
        }

        public void Update(int roomId,int roomTypeID)
        {
            _dbProvider.DB.Execute("update Room set RoomTypeId=@0,Modified=now() where RoomId=@1", roomTypeID,roomId);
        }

        public void SetMending(int roomId, bool isMending)
        {
            _dbProvider.DB.Execute("update Room set IsMending=@0,Modified=now() where RoomId=@1", isMending, roomId);
        }

        public void Remove(int roomId)
        {
            _dbProvider.DB.Delete<Room>(roomId);
        }

        public RoomExtension GetOne(int roomId)
        {
            var sql = new StringBuilder();
            sql.Append(GetRoomBasicSql());
            sql.Append("where r.RoomId=@0 ");
            var ret = _dbProvider.DB.FirstOrDefault<RoomExtension>(sql.ToString(), roomId);
            return ret;
        }
    }
}
